using System.Linq;
using System.Web.Mvc;
using log4net;
using Pixster.Controllers.Helpers;
using Pixster.Models;

namespace Pixster.Controllers
{
    public class PhotoController : Controller
    {
        private static readonly ILog LOG = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public ActionResult Index(string directory, string albumName, string photoName)
        {
            if (string.IsNullOrEmpty(directory))
            {
                LOG.Info("Directory is null, returning to homepage.");
                return RedirectToAction("Index", "Home");
            }

            if (string.IsNullOrEmpty(albumName))
            {
                LOG.InfoFormat("Album is null, returning to Directory '{0}'.", directory);
                return RedirectToAction("Index", "Directory", directory);
            }

            if (string.IsNullOrEmpty(photoName))
            {
                LOG.InfoFormat("Photo is null, returning to Album '{0}'.", albumName);
                return RedirectToAction("Index", "Album", albumName);
            }

            var sitemap = ManifestHelper.Sitemap;

            if (sitemap == null)
            {
                LOG.Info("Sitemap is null, returning to homepage.");
                return RedirectToAction("Index", "Home");
            }

            var dir = sitemap.Where(d => d.SeoName.Equals(directory)).SingleOrDefault();

            if (dir == null || dir.Albums == null)
            {
                LOG.InfoFormat("Cannot find Directory '{0}' or it has no Albums, returning to homepage.", directory);
                return RedirectToAction("Index", "Home");
            }

            var album = dir.Albums.Where(a => a.SeoName.Equals(albumName)).SingleOrDefault();

            if (album == null)
            {
                LOG.InfoFormat("Cannot find Album '{0}', returning to directory.", directory);
                return RedirectToAction("Index", "Directory", directory);
            }

            var photo = album.Photos.Where(p => p.SeoName.Equals(photoName)).SingleOrDefault();

            return View(new PixsterViewModel {Sitemap = sitemap, CurrentDirectory = dir, CurrentAlbum = album, CurrentPhoto = photo});
        }

        public ActionResult Index2()
        {
            return View();
        }

        public ActionResult Index3()
        {
            return View();
        }
    }
}